import { createRouter, createWebHashHistory } from "vue-router";
import { setTitle, getCookie } from "../utils/tools";

const routes = [
  {
    path: "/login",
    name: "login-in",
    meta: {
      title: "登录",
      auth: false,
    },

    component: () => import("../views/login.vue"),
  },

  {
    path: "/chat/:username/:roomid",
    name: "chat",
    meta: {
      title: "聊天",
      auth: false,
    },

    component: () => import("../views/chat/chat.vue"),
  },
  {
    path: "/:pathMatch(.*)*",
    name: "error",
    component: () => import("../components/404.vue"),
  },
];

const router = createRouter({
  history: createWebHashHistory(),
  routes,
});

//路由守卫
router.beforeEach(async (to:any, _from: any, next: (arg0?: any | undefined) => void) => {
  //设置页面标题
  to.meta && setTitle(to.meta.title);
  //判断是否登录
  const token = getCookie();
  next();
  // if (token) {
  //   if (to.name === "login-in") {
  //     next({
  //       name: "chat-in",
  //     });
  //   } else {
  //     next();
  //   }
  // } else {
  //   if (to.name === "login-in") {
  //     next();
  //   } else {
  //     next({
  //       name: "login-in",
  //     });
  //   }
  // }
});

/**
 * 1.导航被触发
 * 2.在失活得组件（即将离开得页面组件）里面调用离开守卫 beforeRouteLeave
 * 3.调用全局得前置守卫 beforeEach
 * 4.在重用得组件里面调用beforeRouteUpdate
 * 5.调用路由独享得守卫 beforeEnter
 * 6.解析异步路由组件
 * 7.在被激活得组件（即将进入得页面组件）里调用beforeRouteEnter
 * 8.调用全局得解析守卫 beforeResolve
 * 9.导航被确认
 * 10.调用全局得后置守卫 afterEach
 * 11.触发DOM更新
 * 12.用创建好的实例调用beforeRouterEnter守卫里传给next的回调函数
 */

export default router;